#include "CRC16.h"

const unsigned short CRC_16_Tab[16] =
{
  0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 
  0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400
};

unsigned short CRC16(unsigned char *puchMsg,unsigned short uiDataLen)
{
    unsigned short wCRC = 0xFFFF;
    unsigned char i;
    unsigned char chChar;

    for (i = 0; i < uiDataLen; i++)
    {
            chChar = *puchMsg++;
            wCRC = CRC_16_Tab[(chChar ^ wCRC) & 15] ^ (wCRC >> 4);
            wCRC = CRC_16_Tab[((chChar >> 4) ^ wCRC) & 15] ^ (wCRC >> 4);
    }
    return wCRC;
}

void CRC16R(unsigned char *puchMsg,unsigned short uiDataLen)
{
    unsigned short wCRC = 0xFFFF;
    unsigned char i;
    unsigned char chChar;

    for (i = 0; i < uiDataLen; i++)
    {
            chChar = *puchMsg++;
            wCRC = CRC_16_Tab[(chChar ^ wCRC) & 15] ^ (wCRC >> 4);
            wCRC = CRC_16_Tab[((chChar >> 4) ^ wCRC) & 15] ^ (wCRC >> 4);
    }
	*puchMsg++ = (unsigned char)wCRC;
    *puchMsg++ = (unsigned char)(wCRC>>8);
}

